<?php
/**
 * Created by PhpStorm.
 * User: Bzing
 * Date: 2017/6/23
 * Time: 11:44
 */
namespace app\api\controller;
use app\models\Models;

class Activity extends Base {
    /**
     * 活动列表
     * @return \think\response\Json
     */
    public function activityList(){
        if(request()->isPost()){
            $post = input('param.');
            $activity = new Models('activity');
            try{
                $params = self::paramsSign(['equipment','encrypt','lng','lat','location','page']);
                // 登录状态下
                if($params['token']){
                    // 登录验证
                    $params = self::checkLogin();
                    // 更新用户位置信息
                    self::updateLocation(['lng'=>$params['lng'],'lat'=>$params['lat'],'location'=>$params['location']],['uid'=>$params['uid']]);
                }
                $join  = [['activity_type c','a.type_id = c.id','left'],['business d','a.bid = d.id','left']];
                $field = 'a.id,a.name,a.image,a.join_num,a.join_min,a.begin_time,a.type_id,c.name type_name,d.name address,d.lng,d.lat';
                $where = ['a.status'=>[['eq',Models::STATUS_ON],['eq',Models::STATUS_READY],'or'],'a.is_delete'=>Models::DELETE_NOT];
                $list  = $activity->_page($where,$field,'',$join,$params['page']);
                $list  = $list->items();
                foreach($list as $k=>$v){
                    $list[$k]['image']    = empty($v['image']) ? '' : array_map([$this,'arrayMapActivity'],json_decode($v['image'],true));
                    $list[$k]['distance'] = getDistance($v['lng'],$v['lat'],$post['lng'],$post['lat']);
                    unset($list[$k]['lng'],$list[$k]['lat']);
                }
                $distance = array_column($list,'distance');   // 获取列数据
                $join_num = array_column($list,'join_num');   // 获取列数据
                array_multisort($distance,SORT_ASC,$join_num,SORT_DESC,$list);    // 多维数组的排序
            } catch (\Exception $e){
                return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            return json(self::formatSuccessResult($list));
        }
    }

    /**
     * 发布活动
     * 第一步选择活动场所以及选座等
     * 第二步选择消费商品并下单
     * 第三步选择代金券
     * 第四步选择支付方式并付款
     * 第五步选择营销接待
     * @return \think\response\Json
     */
    public function activityAdd(){
        if(request()->isPost()){
            try{
                // 登录验证
                $params = self::checkLogin(['equipment','encrypt','name','description','business_id','table_id','join_min','begin_time','join_action']);
                $activity = new Models('activity');
                $order = new Models('order');
                // 获取活动订单信息
                $order_info = $order->_find(['uid'=>$params['uid'],'type_id'=>Models::ORDER_TYPE_EVENT,'status'=>Models::ORDER_PAY_NOT]);
                if($order_info){
                    throw new \LogicException('您有活动订单尚未支付，请前往支付或取消',1032);
                }
                // 获取桌号信息
                $table_info = self::getTableInfo($params['table_id']);
                if($table_info['status'] == Models::STATUS_OFF){
                    throw new \LogicException('该桌尚未开放，请重新选择',1034);
                }
                if($table_info['is_reserve'] == Models::TABLE_YES){
                    throw new \LogicException('该桌已被预订,请重新选择',1027);
                }
                if($table_info['people_max'] < $params['join_min']){
                    throw new \LogicException('人数超出最大范围',1028);
                }
                if(!$_FILES){
                    throw new \LogicException('上传图片不能为空',1033);
                }
                $add = [
                    'uid'         => $params['uid'],
                    'bid'         => $params['business_id'],
                    'name'        => $params['name'],
                    'description' => $params['description'],
                    'type_id'     => empty($params['password']) ? Models::ACTIVITY_TYPE_USER : Models::ACTIVITY_TYPE_PWD,
                    'table_id'    => $params['table_id'],
                    'join_min'    => $params['join_min'],
                    'join_action' => $params['join_action'],
                    'password'    => empty($params['password']) ? '' : password_hash($params['password'],true),
                    'begin_time'  => strtotime($params['begin_time']),
                    'create_time' => time(),
                    'image'       => json_encode(upload('activity'))
                ];
                // 活动表添加纪录
                $activity_id = $activity->_add($add);
                // 用户参加活动关系表添加记录
                $act_join = new Models('activity_join');
                $bool = $act_join->_add(['aid'=>$activity_id,'uid'=>$params['uid'],'is_originator'=>Models::IS_ORIGINATOR,'create_time'=>time()]);
                if(!$activity_id || !$bool){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
                return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            return json(self::formatSuccessResult(['activity_id'=>$activity_id]));
        }
    }

    /**
     * 参加活动
     * @return \think\response\Json
     */
    public function activityJoin(){
        if(request()->isPost()){
            try{
                // 登录验证
                $params = self::checkLogin(['equipment','encrypt','activity_id']);
                // 检查是否有未支付订单
                $order = new Models('order');
                $order_info = $order->_select(['uid'=>$params['uid'],'type_id'=>Models::ORDER_TYPE_EVENT,'status'=>Models::ORDER_PAY_NOT]);
                if($order_info){
                    throw new \LogicException('您有活动订单尚未支付，请前往支付或取消',1032);
                }
                // 检查活动是否存在
                $activity = new Models('activity');
                $info = $activity->_find(['id'=>$params['activity_id']],'id,uid,bid,table_id,join_action,join_min,status');
                if(!$info || $info['status'] != Models::STATUS_READY){
                    throw new \LogicException('活动不存在或已开始',1030);
                }
                // 判断是否参加过该活动
                $act_join = new Models('activity_join');
                $is_join = $act_join->_find(['aid'=>$params['activity_id'],'uid'=>$params['uid'],'status'=>Models::STATUS_ON]);
                if($is_join){
                    throw new \LogicException('您已参加过该活动',1023);
                }
                // 发起人请客择直接添加记录
                $add = ['aid'=>$params['activity_id'],'uid'=>$params['uid'],'create_time'=>time()];
                if($info['join_action'] == Models::MONEY_ALL){
                    $add['status'] = Models::STATUS_ON;
                }
                $act_join = new Models('activity_join');
                $bool = $act_join->_add($add);
                if(!$bool){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
                return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            return json(self::formatSuccessResult(['join_type'=>$info['join_action']]));
        }
    }

    /**
     * 活动详情
     * @return \think\response\Json
     */
    public function activityShow(){
        if(request()->isPost()){
            try{
                $params = self::paramsSign(['equipment','encrypt','activity_id']);
                $activity = new Models('activity');
                $order = new Models('order');
                $act_info = $activity->_find($params['activity_id']);
                if(!$act_info || $act_info['status'] != Models::STATUS_READY || $act_info['status'] != Models::STATUS_ON){
                    throw new \LogicException('活动不存在或已结束',1030);
                }
                // 暗号活动判断暗号
                if(!empty($act_info['password'])){
                    $bool = password_verify($params['password'],$act_info['password']);
                    if(!$bool){
                        throw new \LogicException('暗号错误',1026);
                    }
                }
                // 登录状态下
                if($params['token']){
                    // 登录验证
                    $params = self::checkLogin();
                    // 查询活动用户关系表，判断是否参加过该活动
                    $is_join = $order->_find(['aid'=>$params['activity_id'],'uid'=>$params['uid'],'status'=>Models::ORDER_PAY_YES]);
                }
                $join  = [['business b','a.bid = b.id','left'],['activity_type c','a.type_id = c.id','left']];
                $field = 'a.id,a.uid,a.name,a.description,a.begin_time,a.join_num,a.join_min,a.join_money,a.image,b.name business,b.lng,b.lat,b.location,c.id type_id,c.name type_name';
                $info  = $activity->joinOne($join,['a.id'=>$params['activity_id']],$field);
                // 查询报名成员信息
                $join_user = $order->joinMany([['user b','a.uid = b.id','left']],['a.aid'=>$params['activity_id'],'a.status'=>Models::ORDER_PAY_YES],'b.id,b.portrait','',5);
                foreach($join_user as $k=>$v){
                    $join_user[$k]['portrait'] = empty($v['portrait']) ? '' : self::arrayMapPortrait($v['portrait']);
                    $join_user[$k]['id'] = $v['id'];

                }
                $info['join_user'] = $join_user;
                $info['image']     = empty($info['image']) ? '' : array_map([$this,'arrayMapActivity'],json_decode($info['image'],true));
                // 获取活动须知
                $info['notice']    = self::activityNotice($info['type_id']);
                // 发起人信息
                $info['initiator'] = self::activityInitiator($info['type_id'],$info['uid']);
                $info['is_join']   = empty($is_join) ? Models::JOIN_NOT : Models::JOIN_YES;
                // 添加点击数
                $bool = $activity->setValue(['id'=>$params['activity_id']],'click_num');
                if(!$bool){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
                return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            return json(self::formatSuccessResult($info));
        }
    }

    /**
     * 用户参加或发起的活动列表
     * @return \think\response\Json
     */
    public function userActivity(){
        if(request()->isPost()){
            $params = input('param.');
            $activity = new Models('activity');
            try{
                // 验证签名
                self::sign(['equipment','user_id','page']);
                $join  = [['activity_type b','a.type_id = b.id','left'],['business c','a.bid = c.id','left'],['activity_join d','a.id = d.aid','left']];
                $field = 'a.id,a.name,a.image,a.join_num,a.join_min,a.begin_time,a.type_id,a.status,b.name type_name,c.name address';
                $list['list'] = $activity->_page(['d.uid'=>$params['user_id'],'d.status'=>Models::STATUS_ON],$field,'a.id desc',$join,$params['page']);
                $list['list'] = $list['list']->items();
                foreach($list['list'] as $k=>$v){
                    $list['list'][$k]['image'] = empty($v['image']) ? '' : array_map([$this,'arrayMapActivity'],json_decode($v['image'],true))[0];
                }
                $list['count'] = count($list['list']);
            } catch (\Exception $e){
                return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            return json(self::formatSuccessResult($list));
        }
    }

    /**
     * 拼桌互动列表
     * @return \think\response\Json
     */
    public function shareTableList(){
        if(request()->isPost()){
            try{
                // 验证签名
                $params = self::checkLogin(['equipment','encrypt','page','business_id']);
                $scan = new Models('scan');
                $info = $scan->_find(['status'=>Models::SCAN_YES,'uid'=>$params['uid'],'bid'=>$params['business_id']]);
                if(!$info){
                    throw new \LogicException('请扫码',1041);
                }
                $activity = new Models('activity');
                $where = ['a.status'=>[['eq',Models::STATUS_ON],['eq',Models::STATUS_READY],'or'],'a.is_delete'=>Models::DELETE_NOT,'a.bid'=>$params['business_id']];
                $list = $activity->joinMany([['table b','a.table_id = b.id','left']],$where,'a.id,a.name,a.description,b.name table_name,((a.join_num/a.click_num) *100) hot');
            } catch (\Exception $e){
                return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            return json(self::formatSuccessResult($list));
        }
    }

    /**
     * 用户发起的活动列表
     * @return \think\response\Json
     */
    public function userAddActivity(){
        if(request()->isPost()){
            try{
                // 验证签名
                $params = self::checkLogin(['equipment','encrypt','page']);
                $activity = new Models('activity');
                $join  = [['activity_type b','a.type_id = b.id','left']];
                $field = 'a.id,a.name,a.image,a.join_num,a.join_min,a.begin_time,a.type_id,a.status,b.name type_name';
                $list = $activity->_page(['a.uid'=>$params['uid'],'a.status'=>['<>',Models::STATUS_OFF],'is_delete'=>Models::DELETE_NOT],$field,'a.id desc',$join,$params['page']);
                $list = $list->items();
                foreach($list as $k=>$v){
                    $list[$k]['image'] = empty($v['image']) ? '' : array_map([$this,'arrayMapActivity'],json_decode($v['image'],true))[0];
                }
            } catch (\Exception $e){
                return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            return json(self::formatSuccessResult($list));
        }
    }

    /**
     * 用户参加的活动列表
     * @return \think\response\Json
     */
    public function userJoinActivity(){
        if(request()->isPost()){
            try{
                // 验证签名
                $params = self::checkLogin(['equipment','encrypt','page']);
                $activity = new Models('activity');
                $join  = [['activity_type b','a.type_id = b.id','left'],['business c','a.bid = c.id','left'],['activity_join d','a.id = d.aid','left']];
                $field = 'a.id,a.name,a.image,a.join_num,a.join_min,a.begin_time,a.type_id,a.status,b.name type_name,c.name address';
                $list = $activity->_page(['d.uid'=>$params['uid'],'d.is_originator'=>Models::NOT_ORIGINATOR,'d.status'=>Models::STATUS_ON],$field,'a.id desc',$join,$params['page']);
                $list = $list->items();
                foreach($list as $k=>$v){
                    $list[$k]['image'] = empty($v['image']) ? '' : array_map([$this,'arrayMapActivity'],json_decode($v['image'],true))[0];
                }
            } catch (\Exception $e){
                return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            return json(self::formatSuccessResult($list));
        }
    }

    /**
     * 根据活动类型获取活动须知
     * @param $type_id
     * @return mixed
     */
    function activityNotice($type_id){
        $config = self::getConfig();
        switch ($type_id){
            case Models::ACTIVITY_TYPE_OFFICIAL: $return = $config['activity_notice_official'];break;
            case Models::ACTIVITY_TYPE_BUSINESS: $return = $config['activity_notice_business'];break;
            default: $return = $config['activity_notice_user'];
        }
        return $return;
    }

    /**
     * 根据活动类型返回发起方信息
     * @param $type_id
     * @param $uid
     * @return array|false|\PDOStatement|string|\think\Model
     */
    function activityInitiator($type_id,$uid){
        if($type_id == Models::ACTIVITY_TYPE_BUSINESS){
            $business = new Models('business');
            $info = $business->joinOne([['business_type b','a.type_id = b.id','left']],['a.id'=>$uid],'a.name,a.descrip,a.background,b.name type_name');
            $info['background'] = empty($info['background']) ? '' : self::arrayMapBackground($info['background']);
        } else {
            $user = new Models('user');
            $info = $user->_find($uid,'portrait,nickname,birth,sex,wine,signature');
            $info['age'] = calcAge($info['birth']);
            $info['portrait'] = empty($info['portrait']) ? '' : self::arrayMapPortrait($info['portrait']);
            unset($info['birth']);
        }
        return $info;
    }
}